package wnhz.com.business.shareshop.activity.home;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.constants.Constants;
import wnhz.com.business.groupshop.bean.ShopSKUBean;
import wnhz.com.business.groupshop.bean.SkuAttrBean;
import wnhz.com.business.groupshop.bean.SkuInfoBean;
import wnhz.com.business.groupshop.bean.SkyIdBean;
import wnhz.com.business.groupshop.bean.sku.BaseSkuModel;
import wnhz.com.business.groupshop.bean.sku.ProductModel;
import wnhz.com.business.groupshop.bean.sku.SkuAdapter;
import wnhz.com.business.groupshop.bean.sku.UiData;
import wnhz.com.business.groupshop.ui.AddCartActivity;
import wnhz.com.business.groupshop.ui.ConfirmOrderActivity;
import wnhz.com.business.shareshop.activity.mine.OrderMessageVerifyActivity;
import wnhz.com.business.uitls.BroadCastReceiverUtil;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.decoration.DividerGridItemDecoration;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.MyRecyclerView;

/**
 * 添加购物车(共享商城)
 */
public class AddCartActivityS extends Activity implements View.OnClickListener, BroadCastReceiverUtil.OnReceiveBroadcast {

    @BindView(R.id.iv_left)
    LinearLayout left;
    @BindView(R.id.et_number)
    EditText number;
    @BindView(R.id.iv_right)
    LinearLayout right;
    @BindView(R.id.tv_buy)
    TextView tv_buy;
    @BindView(R.id.tv_tuan)
    TextView tv_tuan;
    @BindView(R.id.rl_max)
    TextView rl_max;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.ll_list)
    LinearLayout ll_list;
    @BindView(R.id.tv_oldPrice)
    TextView tv_oldPrice;
    @BindView(R.id.ry_sku)//sku商品属性列表
    RecyclerView ry_sku;
    @BindView(R.id.tv_sales)//商品属性信息
    TextView tv_sales;
    @BindView(R.id.tv_newPrice)//商品价格
    TextView tv_newPrice;
    @BindView(R.id.tv_collect)
    TextView tv_collect;

    private Context context;
    private String goodsId;
    private SkuInfoBean skuInfoBean;
    private String price;
    private String store;
    private String detail_url;
    private String addressId;
    private String logo_pic;
    private String goodsname;
    private ArrayList<BaseSkuModel> skusAttrList = new ArrayList<>();
    private ArrayList<String> skuKeyList = new ArrayList<>();
    private String skuid = "";

    private String sku_Id = "";//商品属性id
    private String store_id = "";//商户ID
    private String skuinfo = "";//商品属性信息

    private ProductModel testData;
    private UiData mUiData;
    private String SkuKey;
    private BaseSkuModel skuBean;
    private List<SkuInfoBean.InfoBean.SkuBean> skuBean1;
    private SkuAdapter skuAdapter;
    private BroadcastReceiver broadcastReceiver;
    private ShopSKUBean infoBeen = new ShopSKUBean();
    private String skuStatus;//此商品无sku    status= 0     status=1   有sku
    private List<SkuAttrBean> attrBeanList = new ArrayList<>();
    private static final int REQUEST_ADDRESS2 = 222;
    private String store1;

    public static Intent createIntent(Context context, String goodsId,String store_id ,String logo_pic,String goodsname,String storeNum) {
        Intent intent = new Intent(context, AddCartActivityS.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("logo_pic", logo_pic);
        intent.putExtra("store_id", store_id);
        intent.putExtra("goodsname", goodsname);
        intent.putExtra("store",storeNum);
        return intent;
    }

    public void parseIntent() {
        Intent intent = getIntent();
        goodsId = intent.getStringExtra("goodsId");
        logo_pic = intent.getStringExtra("logo_pic");
        store_id = intent.getStringExtra("store_id");
        goodsname = intent.getStringExtra("goodsname");
        store1 = intent.getStringExtra("store");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_add_car2s);
        ButterKnife.bind(this);
        parseIntent();
        Glide.with(this).load(logo_pic).into(iv_avatar);
        tv_collect.setText(goodsname/* + "  库存" + store1 +"件"*/);
        initView();
        initData();
    }

    private void initView() {
        left.setOnClickListener(this);
        right.setOnClickListener(this);
        tv_buy.setOnClickListener(this);
        tv_tuan.setOnClickListener(this);
        rl_max.setOnClickListener(this);

        //中间画横线
        tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        number.setText("1");
        number.postInvalidate();
        //切换后将EditText光标置于末尾
        CharSequence charSequence = number.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    @Override
    public void onClick(View v) {
        int num;
        switch (v.getId()) {
            case R.id.rl_max:
                finish();
                break;
            case R.id.iv_left:
                if (number.getText().toString().equals("")) {
                    ToastUtils.showToast(AddCartActivityS.this, "购物数量不得为空");
                    return;
                }

                num = Integer.parseInt(number.getText().toString());
                num = num - 1;
                if (num <= 1) {
                    ToastUtils.showToast(getBaseContext(), "就剩一件喽！");
                    number.setText(String.valueOf(1));
                } else {
                    number.setText(String.valueOf(num));
                }
                break;
            case R.id.iv_right:
                if (number.getText().toString().equals("")) {
                    ToastUtils.showToast(AddCartActivityS.this, "购物数量不得为空");
                    return;
                }

                num = Integer.parseInt(number.getText().toString());
                num = num + 1;
                number.setText(String.valueOf(num));
                break;
            case R.id.tv_buy:  //单独购买  1-自己开团  2-参团  3-单独购买

                if( chooseSkustarr()){
                    joinCart(Prefer.getInstance().getToken(), goodsId, number.getText().toString());
                }
                break;
            case R.id.tv_tuan:  //立即开团   1-自己开团  2-参团  3-单独购买
                if( chooseSkustarr()){
                    startActivity(ConfirmOrderActivityS.createIntent(AddCartActivityS.this, goodsId, sku_Id, number.getText().toString(),"3",store_id));
                }
                break;
        }
    }

    private boolean chooseSkustarr() {
            if (sku_Id.equals("")||sku_Id==null) {
                ToastUtils.showToast(AddCartActivityS.this, "请选择商品属性");
                return false;
            }

        if (number.getText().toString().equals("") || number.getText().toString().equals("0")) {
            ToastUtils.showToast(AddCartActivityS.this, "购物数量不得为空或0");
            return false;
        }

        if (Integer.valueOf(number.getText().toString()) > Integer.valueOf(store)) {
            ToastUtils.showToast(AddCartActivityS.this, "商品库存不足");
            return false;
        }
        return true;
    }

    private void initData() {
        Map<String, Object> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token", MyApplication.getToken());
        map.put("goodsId", goodsId);
        map.put("store_id", store_id);
        map.put("goods_type", "4");//1.拼团  2.返利  3.免费

        XUtil.Post(Url.GOODS_GETGOODSKU, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("==商品属性sku详情==", result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    skuStatus = jsonObject.optString("status");
                    if (skuStatus.equals("1")) {
                        skusAttrList.clear();
                        skuKeyList.clear();
                        Gson gson = new Gson();
                        infoBeen = gson.fromJson(result, ShopSKUBean.class);
                        Log.e("===商品详情选择商品sku ===", "有sku=");
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        JSONObject jsonObject2 = jsonObject1.optJSONObject("sku_attr");
                        Iterator iterator = jsonObject2.keys();
                        while (iterator.hasNext()) {
                            String key = iterator.next() + "";
                            Gson gson1 = new Gson();
                            String v = jsonObject2.optString(key);
                            SkuAttrBean skuAttrBean = new SkuAttrBean();
                            skuAttrBean = gson1.fromJson(v, SkuAttrBean.class);
                            skuAttrBean.setKey(key);
                            Log.e("SKU详情", "onSuccess:key" + key);
                            attrBeanList.add(skuAttrBean);
                        }
                        infoBeen.getInfo().setSku_attr(attrBeanList);
                        initSkuData();
                    }else{
                        ToastUtils.showToast(AddCartActivityS.this,"暂无可选的商品属性");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });

    }

    private void initSkuData() {
        ry_sku.setLayoutManager(new LinearLayoutManager(AddCartActivityS.this, LinearLayoutManager.VERTICAL, false));
        ry_sku.setAdapter(new BaseRVAdapter(AddCartActivityS.this, infoBeen.getInfo().getSku()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_sku;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                holder.setTextView(R.id.item_one_skuname, infoBeen.getInfo().getSku().get(position).getSkuName());
                RecyclerView recyclerView = (RecyclerView) holder.getView(R.id.recycler_inner);
                recyclerView.setLayoutManager(new GridLayoutManager(AddCartActivityS.this, 3, LinearLayoutManager.VERTICAL, false));
                recyclerView.addItemDecoration(new DividerGridItemDecoration(5));
                final List<ShopSKUBean.InfoBean.SkuBean.DataBean> dataBeen = infoBeen.getInfo().getSku().get(position).getData();
                recyclerView.setAdapter(new BaseRVAdapter(AddCartActivityS.this, dataBeen) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_sku_inner;
                    }

                    private int currentposition = 0;

                    @Override
                    public void onBind(final BaseViewHolder holder, final int position) {
                        if (dataBeen.get(position).getStatus() == 1) {
                            holder.getTextView(R.id.text).setTextColor(getResources().getColor(R.color.red2552));
                            holder.getTextView(R.id.text).setBackground(getResources().getDrawable(R.drawable.b_circle_red255));
                        } else {
                            holder.getTextView(R.id.text).setTextColor(getResources().getColor(R.color.black51));
                            holder.getTextView(R.id.text).setBackground(getResources().getDrawable(R.drawable.b_circle_gray153));
                        }
                        holder.setTextView(R.id.text, dataBeen.get(position).getName());
                        holder.getTextView(R.id.text).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                currentposition = position;

                                for (int i = 0; i < dataBeen.size(); i++) {
                                    if (i == position) {
                                        dataBeen.get(i).setStatus(1);
                                    } else {
                                        dataBeen.get(i).setStatus(0);
                                    }
                                }
                                notifyDataSetChanged();
                                try {
                                    List<Integer> a = new ArrayList<>();
                                    if (infoBeen.getInfo().getSku() != null && infoBeen.getInfo().getSku().size() != 0) {

                                        for (int i = 0; i < infoBeen.getInfo().getSku().size(); i++) {
                                            for (int j = 0; j < infoBeen.getInfo().getSku().get(i).getData().size(); j++) {
                                                if (infoBeen.getInfo().getSku().get(i).getData().get(j).getStatus() == 1) {
                                                    a.add(Integer.parseInt((infoBeen.getInfo().getSku().get(i).getData().get(j).getSku_id())));
                                                }
                                            }
                                        }

                                        Collections.sort(a);
                                        String str = "-";
                                        for (int i = 0; i < a.size(); i++) {
                                            str += a.get(i) + "-";
                                        }
                                        for (int i = 0; i < infoBeen.getInfo().getSku_attr().size(); i++) {
                                            Log.e("==商品属性=", "setData:==1= " + str + "      " + infoBeen.getInfo().getSku_attr().get(i).getKey());
                                            if (str.equals(infoBeen.getInfo().getSku_attr().get(i).getKey())) {
                                                sku_Id = infoBeen.getInfo().getSku_attr().get(i).getSku_id();
                                                store = infoBeen.getInfo().getSku_attr().get(i).getStore();
                                                skuinfo = infoBeen.getInfo().getSku_attr().get(i).getSku_info();
                                                Log.e("sku信息",infoBeen.getInfo().getSku_attr().get(i).getSku_info());
                                                tv_sales.setText(infoBeen.getInfo().getSku_attr().get(i).getSku_info());
                                                tv_newPrice.setText("押金 ¥"+infoBeen.getInfo().getSku_attr().get(i).getPrice());
//                                                tv_goods_store.setText("库存:" + infoBeen.getInfo().getSku_attr().get(i).getStore());
                                                tv_collect.setText(goodsname + "  库存" +store +"件");
                                                break;
                                            }
                                        }

                                    } else {

                                    }
                                } catch (Exception e) {
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    //加入购物车
    private void joinCart(String token, String goodsId, String num) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("goodsId", goodsId);
        if (skuStatus.equals("1")) {
            if (!sku_Id.equals("")) {
                map.put("sku_id", sku_Id);
            }
        }
/**
 * @param str token
 * @param int goodsId   商品id
 * @param int sku_id 	可传
 * @param int num       商品数量
 * @param int goods_type 商城类型1拼团  2返利  3免费 4 :共享商城
 */
        map.put("num", num);
        map.put("goods_type", 4);
        XUtil.Post(Url.CART_JOINCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("--------cart aa-----", "--------cart  aa ----" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))) {
                        BroadCastReceiverUtil.sendBroadcast(AddCartActivityS.this, Constants.ACTION_CART);
                    }
                    ToastUtils.showToast(context, jsonObject.optString("info"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

        });
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Constants.ACTION_UPTATE_SKU_MONEY)) {
            mUiData.getSelectedEntities().clear();
            //存放当前被点击的按钮
            mUiData.getSelectedEntities().clear();
            skuid = "";
            sku_Id = "";
            for (int i = 0; i < mUiData.getAdapters().size(); i++) {
                if (mUiData.getAdapters().get(i).getCurrentSelectedItem() != null) {
                    mUiData.getSelectedEntities().add(mUiData.getAdapters().get(i).getCurrentSelectedItem());
                }
            }

            for (int i = 0; i < mUiData.getSelectedEntities().size(); i++) {
                skuid += "-" + mUiData.getSelectedEntities().get(i).getSku_id();
            }

            skuid = skuid + "-";
            LogUtils.e("=====已选中两个属性====", skuid);

            if (testData.getProductStocks().containsKey(skuid)) {
                SkyIdBean skyIdBean = testData.getProductStocks().get(skuid);
                LogUtils.e("=====已选中两个属性====", "jinlaiel ");
                store = skyIdBean.getStore();
                sku_Id = skyIdBean.getSku_id();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BroadCastReceiverUtil.unRegisterBroadcastReceiver(AddCartActivityS.this, broadcastReceiver);
    }
}
